﻿using AutoMapper;
using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Api.Demain.Entities;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Writh.Command.Permissions;
using System.Diagnostics;

namespace RBAC.Api.Writh.CommandHandler.Permissions
{
    public class AddPermissionCommandHandler : IRequestHandler<AddPermissionCommand, APIResult<object>>
    {
        private readonly IBaseRepositry<Permission> dal;
        private readonly IMapper mapper;
        private readonly ILogger<AddPermissionCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="baseRepositry">仓储接口</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public AddPermissionCommandHandler(
            IBaseRepositry<Permission> baseRepositry, 
            IMapper mapper,
            ILogger<AddPermissionCommandHandler> logger)
        {
            dal = baseRepositry;
            this.mapper = mapper;
            _logger = logger;
        }
        public async Task<APIResult<object>> Handle(AddPermissionCommand request, CancellationToken cancellationToken)
        {
            var stopwatch = Stopwatch.StartNew();
            APIResult<object> result = new APIResult<object>();
            
            try
            {
                _logger.LogInformation("开始处理添加权限请求: {PermissionName}", request.PermissionName);
                
                // 执行业务逻辑
                var model = mapper.Map<Permission>(request);
                await dal.Add(model);
                
                // 设置成功结果
                result.Code = ResultCode.Success;
                result.Message = "添加权限成功";
                
                _logger.LogInformation("成功添加权限 {PermissionName}, ID: {Id}", model.PermissionName, model.Id);
                return result;
            }
            catch (Exception ex)
            {
                // 记录异常
                _logger.LogError(ex, "添加权限时发生错误: {PermissionName}, 错误信息: {Message}", 
                    request.PermissionName, ex.Message);
                
                // 设置失败结果
                result.Code = ResultCode.Fail;
                result.Message = $"添加权限失败: {ex.Message}";
                return result;
            }
            finally
            {
                stopwatch.Stop();
                _logger.LogInformation("处理添加权限请求完成, 耗时: {ElapsedMilliseconds}ms", stopwatch.ElapsedMilliseconds);
            }
        }
    }
}
